package com.demo.crm.springboot3security.controller;

import com.demo.crm.springboot3security.dto.ModuleConfig;
import com.demo.crm.springboot3security.entity.Module;
import com.demo.crm.springboot3security.service.ModuleService;
import com.mybatisflex.core.paginate.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 功能模块控制器
 */
@Tag(name = "功能模块", description = "功能模块相关接口")
@RestController
@RequestMapping("/api/modules")
@RequiredArgsConstructor
public class ModuleController {

    private final ModuleService moduleService;

    @Operation(summary = "创建模块")
    @PostMapping
    @PreAuthorize("hasAuthority('module:create')")
    public ResponseEntity<Module> createModule(@RequestBody ModuleConfig config) {
        return ResponseEntity.ok(moduleService.createModule(config));
    }

    @Operation(summary = "更新模块")
    @PutMapping("/{moduleId}")
    @PreAuthorize("hasAuthority('module:update')")
    public ResponseEntity<Module> updateModule(
            @PathVariable Long moduleId,
            @RequestBody ModuleConfig config) {
        return ResponseEntity.ok(moduleService.updateModule(moduleId, config));
    }

    @Operation(summary = "删除模块")
    @DeleteMapping("/{moduleId}")
    @PreAuthorize("hasAuthority('module:delete')")
    public ResponseEntity<Void> deleteModule(@PathVariable Long moduleId) {
        moduleService.deleteModule(moduleId);
        return ResponseEntity.ok().build();
    }

    @Operation(summary = "获取模块详情")
    @GetMapping("/{moduleId}")
    @PreAuthorize("hasAuthority('module:read')")
    public ResponseEntity<Module> getModule(@PathVariable Long moduleId) {
        return ResponseEntity.ok(moduleService.getModule(moduleId));
    }

    @Operation(summary = "获取模块列表")
    @GetMapping
    @PreAuthorize("hasAuthority('module:read')")
    public ResponseEntity<Page<Module>> listModules(int page, int size) {
        return ResponseEntity.ok(moduleService.listModules(page, size));
    }

    @Operation(summary = "获取模块树")
    @GetMapping("/tree")
    @PreAuthorize("hasAuthority('module:read')")
    public ResponseEntity<List<Module>> getModuleTree() {
        return ResponseEntity.ok(moduleService.getModuleTree());
    }

    @Operation(summary = "启用/禁用模块")
    @PutMapping("/{moduleId}/toggle")
    @PreAuthorize("hasAuthority('module:update')")
    public ResponseEntity<Module> toggleModule(
            @PathVariable Long moduleId,
            @RequestParam boolean enabled) {
        return ResponseEntity.ok(moduleService.toggleModule(moduleId, enabled));
    }
}